<template>
  <el-container class="contain">
    <TreeFilter
      v-show="showTree"
      label="name"
      title="列表"
      :data="treeData"
      :default-value="initParam.departmentId"
      @change="changeTreeFilter"
      class="menu-tree"
      :is-input="false"
      :is-all="false"
      style="width: 180px; height: 100%"
      accordion
    />
    <el-container style="width: calc(100% - 180px)">
      <normalCard :title="currentTitle">
        <div class="select-container">
          <el-select v-model="value" placeholder="Select" class="custom-select" @change="fetchTreeData">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="main-flex">
          <div class="item" v-for="(item, index) in items" :key="index">
            <div class="chartTitle" style="font-size: 25px" @click="navigateToPage(item.title)">{{ item.title }}</div>
            <BarLineChart
              :data="item.data"
              :legend-data="item.legendData"
              :x-label="item.xLabel"
              :rotate="item.rotate"
              ref="barLineChart"
              :key="item.title"
              @bar-click="barClick"
            />
          </div>
        </div>
      </normalCard>
    </el-container>
  </el-container>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted, nextTick } from "vue";
import normalCard from "../../components/normalCard.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import BarLineChart from "@/components/ECharts/components/barLineChart.vue";
import { getManYiDuListApi } from "@/api/modules/manyidu";
import { getWxManYiDuListApi } from "@/api/modules/wxmanyidu";
import { useRouter } from "vue-router";

const router = useRouter();
const treeData = ref<any>([]);
const items = ref<any>([]);
const showTree = ref(true);
const initParam = reactive({ departmentId: "" });
const value = ref<string>("0"); // 添加 select 的值绑定
const barLineChart = ref<any>(null); // 添加图表引用
const options = [
  {
    value: "0",
    label: "季度"
  },
  {
    value: "1",
    label: "期"
  }
];

const fetchTreeData = async () => {
  try {
    // 保存当前选中的节点ID
    const currentSelectedId = initParam.departmentId;
    // 重置数据
    items.value = [];
    treeData.value = [];
    initParam.departmentId = "";

    // 获取新数据
    const [manYiDuRes, wxManYiDuRes] = await Promise.all([
      getManYiDuListApi(options[value.value]),
      getWxManYiDuListApi(options[value.value])
    ]);

    const data = [
      { id: "1", name: "家宽满意度", type: "line", data: manYiDuRes.data },
      { id: "2", name: "无线满意度", type: "line", data: wxManYiDuRes.data }
    ];

    treeData.value = data;

    // 如果之前有选中的节点，继续使用该节点
    // 如果没有，则选择第一个节点
    console.log(currentSelectedId);
    if (currentSelectedId) {
      initParam.departmentId = currentSelectedId;
    } else if (treeData.value.length > 0) {
      initParam.departmentId = treeData.value[0].id;
    }

    await updateContent();

    // 如果需要，重置图表
    if (barLineChart.value) {
      // 如果 barLineChart 是数组
      if (Array.isArray(barLineChart.value)) {
        barLineChart.value.forEach(chart => {
          if (chart && chart.refresh) {
            chart.refresh();
          }
        });
      }
      // 如果 barLineChart 是单个实例
      else if (barLineChart.value.refresh) {
        barLineChart.value.refresh();
      }
    }
  } catch (error) {
    console.error("Failed to fetch data:", error);
    // 可以添加错误提示
  }
};

const currentNode = computed(() => {
  return findNodeById(treeData.value, initParam.departmentId);
});
const currentTitle = computed(() => currentNode.value?.name);

const updateContent = async () => {
  items.value = currentNode.value?.data || [];

  // 确保在下一个 tick 更新图表
  await nextTick();
  if (barLineChart.value) {
    if (Array.isArray(barLineChart.value)) {
      barLineChart.value.forEach(chart => {
        if (chart && chart.refresh) {
          chart.refresh();
        }
      });
    }
  }
};

const findNodeById = (nodes, id) => {
  for (const node of nodes) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
};

const changeTreeFilter = val => {
  initParam.departmentId = val;
  updateContent();
};

// 添加跳转方法
const navigateToPage = async title => {
  router.push({ path: "twoPage", query: { name: title, option: options[value.value].label } });
};

const barClick = (params: any) => {
  console.log(params);
  router.push({ path: "twoPage", query: { name: params.seriesName, barName: params.name, option: options[value.value].label } });
};

onMounted(fetchTreeData);
</script>

<style lang="scss" scoped>
@import "index.scss";
</style>
